export default {
  data: () => {
    return {
      searchText: '',
      tableData: [],
      pagesize: 2,
      total: 0,
      curPage: 1,
      dialogFormVisible: false,
      updateFormVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ]
        // 如果使用正则表达式的话就用pattern关键字
      }
    }
  },
  methods: {
    async userListGet (currentPage, queryText = '') {
      const url = 'users'
      const reqObj = {
        params: {
          query: queryText,
          pagenum: currentPage,
          pagesize: this.pagesize
        }
      }
      const res = await this.axios(url, reqObj)
      this.tableData = res.data.data.users
      this.curPage = res.data.data.pagenum
      this.total = res.data.data.total
      console.log(res)
    },
    currentChange (res) {
      this.curPage = res
      this.userListGet(res, this.searchText)
    },
    search () {
      this.userListGet(this.curPage, this.searchText)
    },
    async updateStatus (row) {
      const { id, mg_state: status } = row
      await this.axios.put(`users/${id}/state/${status}`)
      this.userListGet(1)
    },
    async removeUser (row) {
      const { id } = row
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await this.axios.delete(`users/${id}`)
        this.userListGet(1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      } catch (error) {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    },
    async addUser () {
      try {
        await this.$refs.addForm.validate()
        await this.axios.post('users', this.form)
        this.dialogFormVisible = false
        this.userListGet(1)
      } catch (error) {
        console.log(error)
      }
    },
    updateFormVisibleFun (row) {
      this.updateFormVisible = true
      this.editUserForm = { ...row }
    },
    async updateUser () {
      const { id, mobile, email } = this.editUserForm
      await this.axios.put(`users/${id}`, {
        mobile,
        email
      })
      this.updateFormVisible = false
      this.userListGet(1)
    }
  },
  created () {
    this.userListGet(1)
  }
}
